package com.sjtuy.galtxtreader.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class utils {
    public static File createFileOverWrite(File dir,String fileName) throws IOException {
        if(dir==null||!dir.isDirectory()){
            return null;
        }
        File file = new File(dir.getPath()+"/"+fileName);
        if(file.isDirectory())
            return null;
        if(file.exists())
            file.delete();
        file.createNewFile();
        return file;
    }
    public static boolean deleteDir(File dir){
        for(File file:dir.listFiles()){
            if(file.isDirectory())
                deleteDir(file);
            else
                file.delete();
        }
        return dir.delete();
    }
    public static BufferedReader file2BufferReader(File file) throws FileNotFoundException {
        return new BufferedReader(new FileReader(file));
    }
    public static String file2String(File file) throws IOException {
        BufferedReader br = file2BufferReader(file);
        String tmp;
        StringBuffer sb = new StringBuffer();
        while ((tmp=br.readLine())!=null){
            sb.append(tmp).append("\n");
        }
        return sb.toString();
    }
    public static boolean copy(InputStream from, OutputStream to){
        byte bt[] = new byte[1024];
        int c;
        try{
            while ((c = from.read(bt)) > 0)
            {
                to.write(bt, 0, c);
            }
            from.close();
            to.close();
        }catch (IOException e){
            return false;
        }
        return true;
    }
    public static File openFileInDir(File dir,String fileName){
        if(!dir.isDirectory())
            return null;
        return new File(dir.getPath()+"/"+fileName);
    }
}
